package com.gxb.codebook;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import io.alterac.blurkit.BlurKit;
import io.alterac.blurkit.BlurLayout;

public class RegActivity extends AppCompatActivity {

    private EditText Username;
    private EditText Password;
    private EditText Password2;
    private EditText MiBao1;
    private EditText MiBao2;
    private EditText MiBao3;
    private Button reg_btn;
    private BlurLayout blurLayout;
    private Dialog mDialog;
    private FragmentActivity mActivity;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_reg);

        // 初始化LocalBroadcastManager
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 初始化广播接收器
        themeChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("THEME_CHANGED".equals(intent.getAction())) {
                    recreate();
                }
            }
        };

        // 注册广播接收器
        IntentFilter filter = new IntentFilter("THEME_CHANGED");
        localBroadcastManager.registerReceiver(themeChangeReceiver, filter);

        blurLayout = findViewById(R.id.blurLayout);
        BlurKit.init(this);
        Username = findViewById(R.id.username);
        Password = findViewById(R.id.one_password);
        Password2 = findViewById(R.id.two_password);
        reg_btn = findViewById(R.id.reg_btn);
        MiBao1 = findViewById(R.id.mibao1);
        MiBao2 = findViewById(R.id.mibao2);
        MiBao3 = findViewById(R.id.mibao3);
        mActivity = this;

        reg_btn.setOnClickListener(v -> {
            String username = Username.getText().toString();
            String password = Password.getText().toString();
            String password2 = Password2.getText().toString();
            String mibao1 = MiBao1.getText().toString();
            String mibao2 = MiBao2.getText().toString();
            String mibao3 = MiBao3.getText().toString();

            if (username.isEmpty() || password.isEmpty() || password2.isEmpty() ||
                    mibao1.isEmpty() || mibao2.isEmpty() || mibao3.isEmpty()) {
                Toast.makeText(RegActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();

                // 发送注册信息不完整广播
                Intent incompleteIntent = new Intent("REGISTRATION_INCOMPLETE");
                localBroadcastManager.sendBroadcast(incompleteIntent);
            } else if (!password.equals(password2)) {
                Toast.makeText(RegActivity.this, "两次密码不一致", Toast.LENGTH_SHORT).show();

                // 发送密码不一致广播
                Intent mismatchIntent = new Intent("PASSWORD_MISMATCH");
                localBroadcastManager.sendBroadcast(mismatchIntent);
            } else if (!username.matches("^[A-Za-z0-9@#$%^&*.]+$") ||
                    !password.matches("^[A-Za-z0-9@#$%^&*.]+$")) {
                Toast.makeText(RegActivity.this, "用户名和密码仅支持A-Z,a-z,0-9,@、#、$、%、^、&、*、.",
                        Toast.LENGTH_SHORT).show();

                // 发送格式错误广播
                Intent formatIntent = new Intent("INVALID_FORMAT");
                localBroadcastManager.sendBroadcast(formatIntent);
            } else {
                String wserpasswd = password + "+" + username;
                String encryptedPassword = UserPasswdConfound.encrypt(wserpasswd);
                saveUserInfoToFile(encryptedPassword);
                mibao("你的家乡是：" + mibao1);
                mibao("你的宠物是：" + mibao2);
                mibao("你的学校是：" + mibao3);

                // 复制mibao.txt文件到Downloads文件夹下
                copyMibaoFile();

                showDeveloperWarnDialog();

                // 发送注册成功广播
                Intent successIntent = new Intent("REGISTRATION_SUCCESS");
                successIntent.putExtra("username", username);
                localBroadcastManager.sendBroadcast(successIntent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (localBroadcastManager != null && themeChangeReceiver != null) {
            localBroadcastManager.unregisterReceiver(themeChangeReceiver);
        }
    }

    private void copyMibaoFile() {
        File file = new File(getFilesDir(), "mibao.txt");
        File file2 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "密保.txt");
        try {
            if (!file2.exists()) {
                file2.createNewFile();
            }
            try (FileOutputStream fos = new FileOutputStream(file2, true);
                 FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
            }

            // 发送密保文件复制成功广播
            Intent copyIntent = new Intent("MIBAO_FILE_COPIED");
            localBroadcastManager.sendBroadcast(copyIntent);
        } catch (IOException e) {
            e.printStackTrace();

            // 发送密保文件复制失败广播
            Intent failIntent = new Intent("MIBAO_FILE_COPY_FAILED");
            localBroadcastManager.sendBroadcast(failIntent);
        }
    }

    private void showDeveloperWarnDialog() {
        mDialog = new Dialog(mActivity);
        mDialog.setContentView(R.layout.developer_warn);
        mDialog.setCancelable(false);

        if (mDialog.getWindow() != null) {
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            int widthInDp = 300;
            int widthInPx = (int) (widthInDp * getResources().getDisplayMetrics().density);
            mDialog.getWindow().setLayout(widthInPx, WindowManager.LayoutParams.WRAP_CONTENT);
        }

        mDialog.show();
        Button outbtn = mDialog.findViewById(R.id.dialog_cancel);
        outbtn.setOnClickListener(v -> {
            mDialog.dismiss();

            // 发送开发者警告对话框关闭广播
            Intent dialogIntent = new Intent("DEVELOPER_WARN_DIALOG_CLOSED");
            localBroadcastManager.sendBroadcast(dialogIntent);

            finish();
        });

        // 发送开发者警告对话框显示广播
        Intent showIntent = new Intent("DEVELOPER_WARN_DIALOG_SHOWN");
        localBroadcastManager.sendBroadcast(showIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        blurLayout.startBlur();
        blurLayout.lockView();
    }

    @Override
    protected void onStop() {
        super.onStop();
        blurLayout.pauseBlur();
    }

    private void saveUserInfoToFile(String encryptedPassword) {
        String userInfo = encryptedPassword + "\n";
        File file = new File(getFilesDir(), "user_info.txt");

        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            try (FileOutputStream fos = new FileOutputStream(file, true)) {
                fos.write(userInfo.getBytes());
            }

            // 发送用户信息保存成功广播
            Intent saveIntent = new Intent("USER_INFO_SAVED");
            localBroadcastManager.sendBroadcast(saveIntent);
        } catch (IOException e) {
            e.printStackTrace();

            // 发送用户信息保存失败广播
            Intent failIntent = new Intent("USER_INFO_SAVE_FAILED");
            localBroadcastManager.sendBroadcast(failIntent);
        }
    }

    private void mibao(String encryptedPassword) {
        String userInfo = encryptedPassword + "\n";
        File file = new File(getFilesDir(), "mibao.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            try (FileOutputStream fos = new FileOutputStream(file, true)) {
                fos.write(userInfo.getBytes());
            }

            // 发送密保信息保存成功广播
            Intent saveIntent = new Intent("MIBAO_INFO_SAVED");
            localBroadcastManager.sendBroadcast(saveIntent);
        } catch (IOException e) {
            e.printStackTrace();

            // 发送密保信息保存失败广播
            Intent failIntent = new Intent("MIBAO_INFO_SAVE_FAILED");
            localBroadcastManager.sendBroadcast(failIntent);
        }
    }
}
